import {Dict} from "../types.js";
import fs from "node:fs";
import prettier from "prettier";
import _ from 'lodash'

function genDicts(dict: Dict): string {
    let res = `/**
 * ${dict.comment}
 */
export const ${_.camelCase(dict.name)}Select = [
`
    const assignRows = dict.select.map(item => {
        return `  { label: "${item.label}", value: ${typeof item.value === 'string' ? `"${item.value}"` : item.value} }`
    })
    res += assignRows.join(",\n")
    res += `\n];`
    return res;
}

function genInterfaces(): string {
    let res = `export interface DictSelect {
    label: string;
    value: string | number;
}`
    return res;
}

function genFunctions(type: 'js' | 'ts'): string {
    return `export function translate2Label(select${type === 'ts' ? ': DictSelect[]' : ''}, value${type === 'ts' ? ': string | number' : ''}) {
  const find = select.find((item) => item.value === value);
  if (find) {
      return find.label;
  }
  return undefined;
}

export function translate2Value(select${type === 'ts' ? ': DictSelect[]' : ''}, label${type === 'ts' ? ': string' : ''}) {
  const find = select.find((item) => item.label === label);
  if (find) {
      return find.value;
  }
  return undefined;
}`
}

export async function genFile(path: string, type: 'js' | "ts", dicts: Dict[]) {
    if (!fs.existsSync(path)) {
        fs.writeFileSync(path, "");
    }

    const dictSelectCode = dicts.map(dict => genDicts(dict)).join("\n\n")
    let interfaceCode = ''
    if (type === 'ts') {
        interfaceCode = genInterfaces()
    }
    const functionCode = genFunctions(type)

    const code = dictSelectCode + "\n\n" + interfaceCode + "\n\n" + functionCode

    const formatedCode = await prettier.format(code, {
        filepath: path,
        endOfLine: "lf",
        bracketSpacing: true,
    });
    fs.writeFileSync(path, formatedCode, {encoding: "utf-8"});
}

// async function main() {
//     const string = fs.readFileSync("../target.json", {encoding: "utf-8"});
//     const dicts = JSON.parse(string) as Dict[];
//     await genFile("./target.ts", dicts);
// }
//
// await main();